const _ = require('lodash');
const Tag = require('../../utils/platformTag');
const Url = require('url');

const prefix = '/api/tags';

module.exports = app => {
  const {router, model, middleware} = app;

  /** 从url分析tags */
  router.post(prefix + '/parse-tag', async ctx => {
    const {platform, url} = ctx.request.body;
    const check = Url.parse(url);

    if (!platform)
      return ctx.helper.error('请先选择平台');

    if (platform.tag !== 'douyu')
      return ctx.helper.error('只支持斗鱼平台');

    if (!check.hostname)
      return ctx.helper.error('请输入正确的网址');

    if (check.hostname.indexOf('douyu') === -1)
      return ctx.helper.error('只支持斗鱼平台');

    ctx.body = await Tag.douyu(ctx.request.body.url);
  });

  /** 搜索平台与直播类型 */
  router.get(prefix + '/search-type', async ctx => {
    const word = ctx.query.search;

    if (_.isEmpty(word))
      return ctx.helper.error('请输入关键字');
    ctx.body = await model.PlatformType.findAll(
        {
          include: [
            {model: model.Platform, where: {tag: 'douyu'}},
            {
              model: model.Type,
              where: {name: {[app.Sequelize.Op.like]: '%' + word + '%'}},
            },
          ],
        });
  });

  /** 创建 / 修改 tag */
  router.post(prefix, middleware.checkLogin, async ctx => {
    const {platform_type_id, name, key, url} = ctx.request.body;

    //添加tag，需要初始化
    const pt = await model.PlatformType.findOne({
      where: {id: platform_type_id},
      include: [{model: model.Platform}, {model: model.Type}],
    });
    await model.PlatformTag.create({
      name,
      key,
      url,
      platform_type_id,
      platform_id: pt.platform.id,
      type_id: pt.type.id,
    });

    ctx.body = 'ok';
  });

  /** 读取 tag 列表 */
  router.get(prefix, middleware.checkLogin, async ctx => {
    ctx.body = await model.PlatformTag.findAll({
      include: [{model: model.Platform}, {model: model.Type}],
    });
  });

  /** 删除 tag */
  router.post(prefix + '/remove', middleware.checkLogin, async ctx => {
    if (_.isEmpty(ctx.request.body))
      return ctx.helper.error('没有选择标签 1');

    const tags = await model.PlatformTag.findAll(
        {where: {id: {[app.Sequelize.Op.in]: ctx.request.body}}});
    if (tags.length === 0)
      return ctx.helper.error('没有选择标签 2');
    tags.forEach(tag => {
      tag.destroy();
    });
    ctx.body = 'ok';
  });
};

